# -*- coding: utf-8 -*-
from datetime import date
import string
import random
from flask import Blueprint, g
from common.response import success, error
from common.error_code import ErrorCode
from filter.auth import auth_required
from filter.decorators import validate_request, require_role
from model.request import CreateTeacherRequest, TeacherAccountRegisterRequest, CreateStudentRequest
from dao.user_dao import User, Teacher, Student, Class, TeacherStudentManagement
from dao.db import db

register_bp = Blueprint('register', __name__, url_prefix='/api/register')

def generate_random_password(length=8):
    """生成随机字母数字组合密码"""
    chars = string.ascii_letters + string.digits
    return ''.join(random.choice(chars) for _ in range(length))

def is_password_hash_unique(password_hash):
    """检查密码哈希是否已存在"""
    return not Teacher.query.filter_by(password_hash=password_hash).first()

def generate_unique_password_hash():
    """生成不重复的8位随机密码哈希"""
    while True:
        password_hash = generate_random_password(8)
        if is_password_hash_unique(password_hash):
            return password_hash

@register_bp.route('/teacher', methods=['POST'])
@auth_required
@require_role(['admin'])  # 仅管理员可调用
@validate_request(CreateTeacherRequest)
def create_teacher():
    """管理员创建教师接口"""
    data = g.request_data

    # 1. 验证管理员口令
    # 注意：管理员的口令存储在 teachers.password_hash 中
    admin_user_id = g.user_id
    admin_teacher = Teacher.query.filter_by(user_id=admin_user_id).first()
    if not admin_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if admin_teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员口令错误")

    # 2. 在 users 表创建记录
    new_user = User(
        username='',  # 空字符串
        password='',  # 空字符串
        name=data.name,
        role='teacher'
    )
    db.session.add(new_user)
    db.session.flush()  # 刷新以获取新用户ID

    # 3. 在 teachers 表创建记录
    password_hash = generate_unique_password_hash()
    new_teacher = Teacher(
        user_id=new_user.id,
        position=data.position,
        class_id=None,
        password_hash=password_hash
    )
    db.session.add(new_teacher)
    db.session.commit()

    return success({
        "teacher_id": new_teacher.id,
        "user_id": new_user.id,
        "password_hash": password_hash  # 返回生成的教师口令
    })

@register_bp.route('/teacher-account', methods=['POST'])
@validate_request(TeacherAccountRegisterRequest)
def teacher_account_register():
    """教师注册账号接口"""
    data = g.request_data

    # 1. 查找教师口令对应的记录
    teacher = Teacher.query.filter_by(password_hash=data.teacher_password).first()
    if not teacher:
        return error(ErrorCode.INVALID_PARAM, "教师口令错误")

    # 2. 查找对应的用户记录
    user = User.query.get(teacher.user_id)
    if not user:
        return error(ErrorCode.USER_NOT_FOUND, "关联的用户不存在")

    # 3. 检查 username 和 password 是否为空
    if user.username != '' or user.password != '':
        return error(ErrorCode.FORBIDDEN, "该教师已经注册过账号，无法重复注册")
    
    # 4. 检查 username 是否重复
    if User.query.filter_by(username=data.username).first():
        return error(ErrorCode.INVALID_PARAM, "用户名已存在，请更换")

    # 5. 更新 username 和 password
    user.username = data.username
    user.password = data.password  # 注意：生产环境中应哈希存储
    db.session.commit()

    return success({
        "user_id": user.id,
        "username": user.username,
        "name": user.name,
        "role": user.role
    })

@register_bp.route('/student', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(CreateStudentRequest)
def create_student():
    """教师创建学生账号接口"""
    data = g.request_data

    # 1. 验证管理员口令
    admin_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not admin_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if admin_teacher.password_hash != data.teacher_password:
        return error(ErrorCode.INVALID_PARAM, "管理员口令错误")

    # 2. 检查班级是否存在
    cls = Class.query.get(data.class_id)
    if not cls:
        return error(ErrorCode.NOT_FOUND, "班级不存在")

    # 3. 检查班级是否已毕业
    if cls.grade >= 10:
        return error(ErrorCode.FORBIDDEN, "该班级已毕业，不能新增学生")

    # 4. 检查教师权限（admin 跳过）
    if g.role == 'teacher':
        teacher = Teacher.query.filter_by(user_id=g.user_id).first()
        if not teacher or teacher.id != cls.head_teacher_id:
            return error(ErrorCode.FORBIDDEN, "你不是该班级的班主任，无权新增学生")

    # 5. 检查学号在本班级是否重复
    if Student.query.filter_by(class_id=data.class_id, student_id=data.student_id).first():
        return error(ErrorCode.INVALID_PARAM, "该学号在本班级已存在")

    # 6. 生成 username 和 password
    username = f"ST{data.class_id}{data.student_id}"
    password_plaintext = "1234"

    # 7. 创建用户记录
    new_user = User(
        username=username,
        password=password_plaintext,
        name=data.name,
        role='student'
    )
    db.session.add(new_user)
    db.session.flush()  # 获取新用户ID

    # 8. 创建学生记录
    new_student = Student(
        user_id=new_user.id,
        student_id=data.student_id,
        class_id=data.class_id
    )
    db.session.add(new_student)
    db.session.flush()

    # 9. 创建教师-学生管理关系
    manage_teacher_id = cls.head_teacher_id
    if g.role == 'teacher':
        manage_teacher_id = teacher.id
    elif g.role == 'admin' and manage_teacher_id == None:
        manage_teacher_id = admin_teacher.id

    # 注意：start_date 使用 date.today()
    management_record = TeacherStudentManagement(
        teacher_id=manage_teacher_id,
        student_id=new_student.id,
        start_date=date.today()
        # end_date 留空（NULL）
    )
    db.session.add(management_record)

    db.session.commit()

    # 10. 返回账号密码信息
    return success({
        "username": username,
        "password": password_plaintext,  # 返回明文密码仅用于首次创建提示
        "user_id": new_user.id,
        "student_id": new_student.student_id,
        "class_id": new_student.class_id
    })